﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using MailKit.Net.Smtp;
using Microsoft.AspNetCore.Identity.UI.Services;
using MimeKit;
using MimeKit.Text;
using Eqwww.Config;

namespace Eqwww.Web
{
    public class EmailSender : IEmailSender
    {

        private IEmailConfigProvider _emailConfigProvider;
        public EmailSender(IEmailConfigProvider emailConfigProvider)
        {
            _emailConfigProvider = emailConfigProvider;
        }

        public Task SendEmailAsync(string email, string subject, string htmlMessage)
        {
            var emailConfig = _emailConfigProvider.Load();
            var message = new MimeMessage();
            message.From.Add(new MailboxAddress(emailConfig.FromName, emailConfig.FromAddress));
            message.To.Add(new MailboxAddress(email, email));
            message.Subject = subject;

            TextPart body = new TextPart(TextFormat.Html)
            {
                Text = htmlMessage
            };
            message.Body = body;

            using (SmtpClient client = new SmtpClient())
            {
                client.Connect(emailConfig.SmtpServer, emailConfig.SmtpPort, emailConfig.SSL);
                client.Authenticate(emailConfig.Login, emailConfig.AuthCode);
                client.Send(message);
                client.Disconnect(true);
            }
            return Task.CompletedTask;
        }
    }
}
